'use strict';

const Controller = require('egg').Controller;
const dayjs = require('dayjs');
const _ = require('lodash');
const jwt = require('jsonwebtoken');
var authData = require('./authData');
var redis = require('./redis');
const svgCaptcha = require('svg-captcha');
const Mock = require('mockjs');
const Random = Mock.Random;

/**
 * @Controller 认证
 */
class AuthController extends Controller {
  /**
   * @summary 模拟用户列表
   * @description 模拟用户列表  success: 1,
   * @Router GET /mock-api/auth/userList
   * @Response 200 User ok
   */
  async userList() {
    const { ctx } = this;
    console.log('userList --> ', dayjs().format('YYYY-MM-DD HH:mm:ss'));
    console.log('userList --> ', ctx.request.body);

    ctx.body = {
      code: 200,
      data: {
        userList: authData.users,
      },
      msg: '模拟用户列表',
    };
  }

  /**
   * @summary 模拟用户登录
   * @description 模拟用户登录  success: 1,
   * @Router POST /mock-api/auth/login
   * @request body loginPhonePassword *body
   * @Response 200 User ok
   */
  async login() {
    const { ctx } = this;
    console.log('login --> ', dayjs().format('YYYY-MM-DD HH:mm:ss'));
    console.log('login --> ', ctx.request.body);

    let { phone, password, captcha } = ctx.request.body;

    // 校验 验证码
    const sessionCaptcha = ctx.session.captcha;
    if (captcha) {
      if (captcha.toLocaleLowerCase() != sessionCaptcha.toLocaleLowerCase()) {
        console.log(captcha, sessionCaptcha, 'captcha != sessionCaptcha');
        ctx.body = {
          code: 200,
          data: {
            success: 2,
            captcha,
            sessionCaptcha,
          },
          msg: '验证码不对',
        };
        return;
      }
    }

    let userData = {};
    authData.users.forEach((user, idx) => {
      if (user.phone == phone) {
        if (user.password == password) {
          userData = user;
          authData.users[idx].money++;
          authData.users[idx].lastTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
          let perms = [];
          if (userData.role && userData.role.perms) {
            perms = userData.role.perms.map((p) => {
              return p.key;
            });
          }
          ctx.body = {
            code: 200,
            data: {
              success: 1,
              userInfo: userData,
              router: userData.role.routers,
              perms,
              token: jwt.sign(user, this.config.JWT_CONFIG.key, {
                expiresIn: 30 * 60,
              }),
              time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
            },
            msg: '登录成功',
          };
          return;
        } else {
          ctx.body = {
            code: 200,
            data: {
              success: 0,
              phone,
              password,
            },
            msg: '用户名或密码错误',
          };
          return;
        }
      }
    });
    console.log('userData.id = ', userData.id);
    if (!userData.id) {
      ctx.body = {
        code: 200,
        data: {
          success: 0,
        },
        msg: '用户名不存在',
      };
    }
  }

  /**
   * @summary 模拟 获取用户信息
   * @description 模拟 获取用户信息
   * @Router POST /mock-api/auth/userInfo
   * @request header token token
   * @request body userInfo body
   * @Response 200 User ok
   */
  async userInfo() {
    const { ctx } = this;
    console.log('userInfo --> ', dayjs().format('YYYY-MM-DD HH:mm:ss'));
    console.log('ctx.locals --> ', ctx.locals);
    console.log('userInfo --> ', ctx.request.body);
    let times = Number(dayjs().format('ss'));
    let userId = ctx.request.body.userId || ctx.locals.user.id;
    // userId = userId || 100;

    let userIndex = _.findIndex(authData.users, (user) => {
      return user.id == userId;
    });
    console.log(userIndex);

    if (userIndex == -1) {
      ctx.body = {
        code: 200,
        data: {
          success: 0,
        },
        msg: '找不到这个用户，token是否过期',
      };
      return;
    }

    console.log(userIndex);

    authData.users[userIndex].money--;

    ctx.body = {
      code: 200,
      data: {
        success: 1,
        locals: ctx.locals,
        userId,
        userInfo: authData.users[userIndex],
        time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      },
      msg: '获取用户信息成功',
    };
  }

  /**
   * @summary 退出登录
   * @description 系统退出登录 日期
   * @Router POST /mock-api/auth/loginOut
   */
  async loginOut() {
    const { ctx } = this;
    console.log('loginOut --> ', dayjs().format('YYYY-MM-DD HH:mm:ss'));
    console.log('loginOut --> ', ctx.request.body);
    let times = Number(dayjs().format('ss'));
    ctx.body = {
      code: 200,
      data: {
        times,
      },
      msg: '退出登录成功',
    };
  }

  /**
   * @summary 用户手机号注册
   * @description 用户手机号注册
   * @Router POST /mock-api/auth/register
   * @request body registerPhonePassword *body
   */
  async register() {
    const { ctx } = this;
    console.log('register --> ', dayjs().format('YYYY-MM-DD HH:mm:ss'));
    console.log('register --> ', ctx.request.body);
    let times = Number(dayjs().format('ss'));
    let user = {
      id: Date.now(),
      name: ctx.request.body.name || Mock.mock('@cname()'),
      gender: 1,
      phone: ctx.request.body.phone || '177' + (Date.now() % 100000000),
      password: 123456,
      avatar: Random.image('200x200', Random.color()),
      money: Date.now(),
      role: [],
    };
    authData.users.push(user);

    ctx.body = {
      code: 200,
      data: {
        user,
        userlist: authData.users,
      },
      msg: '注册成功',
    };
  }

  /**
   * @summary 获取图形验证码
   * @description 用户手机号注册
   * @Router GET /mock-api/auth/captcha
   */
  async captcha() {
    const { ctx } = this;
    const captchaObj = svgCaptcha.create({}); // captche={text,data}
    console.log('captchaObj.text ---> ', captchaObj.text);
    ctx.session.captcha = captchaObj.text; // 把文本信息存放到会话中的captcha属性中
    ctx.set('Content-Type', 'image/svg+xml');
    let now = Date.now();
    let data = {
      id: now,
      text: captchaObj.text,
      picStream: captchaObj.data,
      createTime: now,
      date: dayjs(now).format('YYYY-MM-DD HH:mm:ss'),
    };
    redis.captchaList.push(data);
    ctx.body = captchaObj.data;
  }
}

module.exports = AuthController;
